<template>
	<view class="content">
		<view class="cu-bar bg-white solid-bottom margin-top">
			<view class="action mj-title" >
				<text class="cuIcon-title text-orange ">解析</text>
				<button class="cu-btn round sm bg-blue" v-show="!openManual" @click="manuallyAdd()">手动新增</button>
				<button class="cu-btn round sm bg-grey" v-show="openManual" @click="manuallyAddExit()">退出</button>
			</view>
		</view>
		<view class="top padding-sm bg-white" v-show="!openManual">
			<view class="padding-bottom-sm">
				<u-upload ref="uUpload" :action="action" :multiple="true" name="files" :auto-upload="false" 
				@on-remove="onRemove"
				@on-choose-complete="onChooseComplete"
					:header="uploadHeader" :max-count="30" :show-tips="false" ></u-upload>
			</view>
			<view class="flex">
				<!-- <u-button @click="removes()" class="margin-right-sm flex-sub" >清空列表</u-button> -->
				<u-button throttle-time="2000"  @click="uploadParse()" class="flex-sub" >1.上传解析</u-button>
			</view>
			
		</view>
		<view class="" v-for="(item,index) in parseList">
			<view class="cu-bar bg-white solid-bottom margin-top">
				<view class="action mj-title" >
					<text>
						<text class="cuIcon-title text-orange " v-if="parseList[0].gameId1">结果 {{index+1}}</text>
						<text class="cuIcon-title text-orange " v-else>手动新增{{index+1}}</text>
					</text>

					<view>
						<u-icon v-show="!openManual" @click="deleteRepeatData(index)" name="close-circle" size="40"></u-icon>
						<u-icon v-show="openManual" @click="copyMauuallyData(index)" name="plus-circle" size="40"></u-icon>
						<u-icon v-show="openManual && index > 0" @click="deleteMauuallyData(index)" name="minus-circle" size="40"></u-icon>
					</view>
				</view>
			</view>
			<view class="">
				<view class="bottom  bg-white">
					<view class="">
						<view class="padding" v-show="!openManual">
							<u-image width="100%" height="300rpx"
								:src="item.localImgUrl"></u-image>
						</view>
						<form>
							<view class="flex">
								<view class="cu-form-group" style="width: 100%; flex: 1;">
									<view class="title" >日期</view>
									<input disabled placeholder="请选择时间" name="input" :value="item.startTime"  @click="showPicker(item)"></input>
									<u-picker @confirm="confirmDate($event,item)" :default-time="item.startTime" :params="{
											year: true,
											month: true,
											day: true,
											hour: true,
											minute: true,
											second: true
										}" v-model="item.showPicker" mode="time" ></u-picker>
								</view>
							</view>
							<view class="flex">
								<view class="cu-form-group ">
									<view class="title">玩家1</view>
									<input disabled name="input" :value="item.gameUser1" @click="showUserPicker(item,'gameUser1')"></input>
									<u-picker mode="selector" @confirm="confirmGameUser($event,item)"  :range="allGameUserList" range-key="value"
									 v-model="item.showUserPicker" ></u-picker>
								</view>
								<view class="cu-form-group">
									<view class="title">分数</view>
									<input name="input" type="text" v-model="item.val1"></input>
								</view>
							</view>
							<view class="flex">
								<view class="cu-form-group ">
									<view class="title">玩家2</view>
									<input disabled name="input" :value="item.gameUser2" @click="showUserPicker(item,'gameUser2')"></input>
								</view>
								<view class="cu-form-group">
									<view class="title">分数</view>
									<input name="input" type="text" v-model="item.val2"></input>
								</view>
							</view>
							<view class="flex">
								<view class="cu-form-group ">
									<view class="title">玩家3</view>
									<input disabled name="input" :value="item.gameUser3" @click="showUserPicker(item,'gameUser3')"></input>
								</view>
								<view class="cu-form-group">
									<view class="title">分数</view>
									<input name="input"  type="text" v-model="item.val3"></input>
								</view>
							</view>
							<view class="flex">
								<view class="cu-form-group ">
									<view class="title">玩家4</view>
									<input disabled name="input" :value="item.gameUser4" @click="showUserPicker(item,'gameUser4')"></input>
								</view>
								<view class="cu-form-group">
									<view class="title">分数</view>
									<input name="input" type="text" v-model="item.val4"></input>
								</view>
							</view>
						</form>
						<u-gap height="5" bg-color="#e6e6e6"></u-gap>
					</view>
				</view>
			</view>
		</view>
		<view class="padding-sm">
			<u-button @click="saveData()">2.确认新增</u-button>
		</view>
	</view>
</template>

<script>
	import globalConfig from '@/common/config.js'
	export default {
		data() {
			return {
				action: globalConfig.url + '/majiang/system/majiang/imageOcr',
				imageUrl: globalConfig.url+"/images/detail",
				uploadHeader: {
					Authorization: ""
				},
				hasRepeatPic: false,
				fileList:[],//文件实时列表
				parseList: [],//解析数据
				parseListTmp:[],//解析数据临时保存
				openManual:false,
				allGameUserList:[],
				gameUserPick:''
			}
		},
		created() {
			
		},
		onShow() {
			//https://cdn.jy520.fun/superbed/2021/12/30/61cd28d62ab3f51d91780314.jpg
			this.uploadHeader.Authorization = this.vuex_token;
		},
		onLoad() {
			if(this.hasAuthUser() ||
				this.vuex_user.gameUser== '沉浮一世' ||
				this.vuex_user.gameUser== 'Lang') {
				this.allGameUser();
			} else {
				uni.switchTab({
				    url: '/pages/tabbar/tabbar-2/tabbar-2'
				});
			}
		},
		methods: {
			allGameUser(){
				this.$u.api.allGameUser(this.parseList).then(res => {
					res.rows.splice(0,1);
					this.allGameUserList = res.rows;
				})
			},
			confirmGameUser(e,item){
				item[this.gameUserPick] = this.allGameUserList[e[0]].value;
			},
			confirmDate(e,item){
				let date = e.year+'-'+ e.month+'-'+e.day+' '+e.hour+':'+e.minute+':'+e.second;
				item.startTime = date;
			},
			showUserPicker(item,gameUserPick){
				this.gameUserPick = gameUserPick;
				item.showUserPicker = true;
			},
			showPicker(item){
				item.showPicker = true;
			},
			copyMauuallyData(index) {
				this.parseList.push(JSON.parse(JSON.stringify(this.parseList[index])));
			},
			deleteMauuallyData(index) {
				this.parseList.splice(index,1);
			},
			manuallyAdd(){
				//手动新增模式
				this.parseListTmp = this.parseList;
				this.parseList = [];
				this.openManual = true;
				this.parseList.push({
					openManual:true,
					showPicker:false,
					showUserPicker:false,
					gameId1: undefined,
					gameId2: undefined,
					gameId3: undefined,
					gameId4: undefined,
					gameUser1: undefined,
					gameUser2: undefined,
					gameUser3: undefined,
					gameUser4: undefined,
					imageUrl: undefined,
					localImgUrl: undefined,
					startTime: undefined,
					successImageName: undefined,
					val1: undefined,
					val2: undefined,
					val3: undefined,
					val4: undefined,
					})
			},
			manuallyAddExit(){
				this.parseList = [];
				this.parseList = this.parseListTmp;
				this.openManual = false;
			},
			//删除一张图片的回调，lists这是成功删除一个图片后，还剩余的图片集合
			onRemove(index, lists,name){
				//级联删除列表
				if(this.parseList.length>0){
					this.parseList = this.parseList.filter(e=>lists.findIndex(item=>e.localImgUrl==item.url)!=-1);
				}
				this.fileList = lists;
				this.checkRepeat();
			},
			onChooseComplete(lists) {
				this.fileList = lists;
				this.checkRepeat();
			},
			deleteRepeatData(index) {
				//级联删除图片
				let fileIndex = this.$refs.uUpload.lists.findIndex(e=>e.url == this.parseList[index].localImgUrl);
				this.$refs.uUpload.remove(fileIndex)
				this.parseList.splice(index,1);
			},
			checkRepeat() {
				let lists = this.fileList;
				this.hasRepeatPic = false;
				for (var i=0; i<lists.length; i++) {
					for (var j=i+1; j<lists.length; j++) {
						if (lists[i].file.size == lists[j].file.size) {
							this.hasRepeatPic = true;
						}
					}
				}
			},
			removes(){
				let _this = this;
				uni.showModal({
				    title: '提示',
				    content: '是否清空列表?',
				    success: function (res) {
				        if (res.confirm) {
							_this.$refs.uUpload.clear();
							_this.parseList = [];
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
			},
			saveData(){
				this.$u.api.checkAndSave(this.parseList).then((res) => {
					if(res.code == 500) {
						//异常
						uni.showToast({
							title: res.msg,
							icon: 'error',
							duration: 2000
						});
					} else if(res.code == 200 || res.code == 0){
						//保存成功
						uni.showToast({
							title: '保存成功',
							icon: 'success',
							duration: 2000
						});
						setTimeout(()=>{
							if(this.openManual) {
								this.manuallyAddExit();
							} else {
								uni.switchTab({
									url: '/pages/tabbar/tabbar-4/tabbar-4'
								});	
							}
						},2000);
					} else {
						//异常
						uni.showToast({
							title: '系统异常',
							icon: 'error',
							duration: 2000
						});
					}
					
				})
			},
			uploadParse() {
				if(this.hasRepeatPic) {
					uni.showToast({
						title: '截图有重复,请检查',
						icon: 'error',
						duration: 2000
					});
					return;
				}
				let _this = this;
				let fileArr = [];
				this.$refs.uUpload.lists.map((item, i) => fileArr.push(item.url));
				//只保留列表里不存在的图片上传
				fileArr = fileArr.filter(e=>this.parseList.findIndex(item=>e == item.localImgUrl)==-1);
				if(fileArr.length<1 && this.parseList.length == 0){
					uni.showToast({
						title: '请至少上传一张截图',
						icon: 'error',
						duration: 2000
					});
					return;
				}
				if(fileArr.length<1 && this.parseList.length > 0){
					uni.showToast({
						title: '解析成功',
						icon: 'error',
						duration: 2000
					});
					return;
				}
				uni.showModal({
				    title: '提示',
				    content: '由于此次数据录入由您负责,请确保截图正确?',
				    success: function (res) {
				        if (res.confirm) {
							uni.showLoading({
								title: '解析中...',
								mask:true
							});
							let count = 0;
							//_this.parseList = [];
				            fileArr.forEach(e => {
				            	uni.uploadFile({
				            		url: _this.action,
				            		filePath: e,
				            		name:'files',
				            		header:{
				            			"Content-Type": "multipart/form-data",
				            			"Authorization": _this.uploadHeader.Authorization
				            		},
				            		success(res) {
				            			let resp = JSON.parse(res.data);
										if(resp.code == 200 || resp.code == 0) {
											resp.data[0].localImgUrl = e;
											 _this.parseList.push(resp.data[0]);
											count++;
										} else if(resp.code == 500) {
											uni.showToast({
												title: '系统异常',
												icon: 'error',
												duration: 2000
											});
										}
				            		},fail(res) {
										count++;
				            			console.log(res);
				            		}
				            	});
				            });
							let hideInterval = setInterval(_=>{
								if(count == fileArr.length){
									uni.hideLoading();
									clearInterval(hideInterval);
								}
							},100)
				        } else if (res.cancel) {
				            console.log('用户点击取消');
				        }
				    }
				});
			},
			hasAuthUser() {
				let userList = this.vuex_user.auth_user_import;
				for (var i = 0; i < userList.length; i++) {
					let user = userList[i];
					if(user == this.vuex_user.gameUser) {
						return true;
					}
				}
				return false;
			}
		}
	}
</script>

<style lang="stylus">
	.mj-title
		justify-content: space-between!important
		width: 100%;
	.flex 
		.cu-form-group 
			border-top 1rpx solid #eee
			
</style>
